package com.ellecity06.cwhiskymall.ui.home.good

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.layoutmanager.QuickGridLayoutManager
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.databinding.LayoutEmptyViewBinding
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.GoodsAdapter
import com.ellecity06.cwhiskymall.databinding.FragmentGoodBinding
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import kotlinx.coroutines.flow.asStateFlow

/**
 * @author ellecity06
 * @time 2024/10/24 19:24
 * @des
 */
class GoodFragment : BaseMvvmFragment<FragmentGoodBinding, GoodViewModel>(),
    TrailingLoadStateAdapter.OnTrailingListener {
    private val brandId: Int by lazy { arguments?.getInt(BRAND_ID) ?: 0 }
    private var adapter: GoodsAdapter? =null
    override fun lazyInit() {
        refreshGood()
        collectState()
        initEvent()
    }

    private fun initEvent() {
        adapter?.setOnItemClickListener { _, _, position ->
            val item = adapter!!.getItem(position)
            WebHelper.goodDetails(requireActivity(), item?.id)
        }
    }

    private fun refreshGood() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(GoodIntent.Goods(brandId))
        }
    }

    private fun loadGood() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(GoodIntent.Goods(brandId, true))
        }
    }

    private fun collectState() {
        viewModel.mState.asStateFlow().observeEvent(this) {
            when (it) {
                is GoodState.RefreshGoods -> {
                    adapter?.submitList(it.list)
                    if (it.list.isEmpty()) {
                        adapterHelper?.trailingLoadState = LoadState.None
                    } else {
                        adapterHelper?.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                    }

                }
                is GoodState.LoadMoreGoods -> {
                    adapter?.addAll(it.list)
                    adapterHelper?.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                }
                else -> {}
            }
        }
    }

    private  var adapterHelper: QuickAdapterHelper?=null
    private val emptyViewBinding by lazy {
        LayoutEmptyViewBinding.inflate(
            layoutInflater,
            binding.rv,
            false
        )
    }

    override fun initView() {
        super.initView()
        val layoutManager = QuickGridLayoutManager(requireActivity(), 2)
        binding.rv.layoutManager = layoutManager
        binding.rv.addGridDecoration(size = R.dimen.dp_7)
        val loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(this)
        adapter = GoodsAdapter()
        adapterHelper = QuickAdapterHelper.Builder(adapter!!)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()
        adapter?.emptyView = emptyViewBinding.root
        adapter?.isEmptyViewEnable = true
        binding.rv.adapter = adapterHelper?.adapter


    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentGoodBinding {
        return FragmentGoodBinding.inflate(LayoutInflater.from(requireActivity()), container, false)
    }

    companion object {
        private const val BRAND_ID = "key_brand_id"

        @JvmStatic
        fun newInstance(brandId: Int): GoodFragment {
            val goodFragment = GoodFragment()
            val bundle = Bundle().apply {
                putInt(BRAND_ID, brandId)
            }
            goodFragment.arguments = bundle
            return goodFragment
        }

    }


    override fun onDestroyView() {
        viewModel.reset()
        super.onDestroyView()
        adapter = null
        adapterHelper=null

    }
    override fun onFailRetry() {
        refreshGood()
    }

    override fun onLoad() {
        loadGood()
    }
}